// JavaScript Document
var http = require('http');
var fs = require('fs');
var dao = require('./dao.js');

/*
 * Constants
 */
var filename = 'fog1.2.2.html';

var webserver  = http.createServer( function (req, res) {
	fs.readFile(filename, 'utf8', function (err, data) {
		res.writeHead(200, { 'Content-Type': 'text/html' });
		res.end(data);
	});
});

// create socket server
var io = require('socket.io').listen(webserver);
io.set('log level', 1);

/*
 * utility functions
 */ 
var createCell = function(id) {
	coord = id.split('x');
	var x = Number(coord[0].replace('g', ''));
	var y = Number(coord[1].replace('y', ''));
	
	var cell = new dao.GridModel({
		_id: id,
		gridx: x,
		gridy: y
	});
	
	return cell;
};

var updateRelativeCell = function(id, cell, data, relative, nearby) {
	console.log('update relative cell... id: ' + id);
	
	if (cell == null) {
		cell = createCell(id);
	}

	if (cell.class == null) {
		// if grid cell is empty
		cell.relative[relative] = 1;
		cell.nearby[nearby] = 1;
		cell.class = 'relaempty';
		cell.key_id = data.key_id;
		cell.keyword = data.keyword;
		cell.color = data.fill;
		
		cell.markModified('relative');
		cell.markModified('nearby');
		cell.save();
		
		io.sockets.emit('registpushN', cell);
	}
	else if (cell.class == 'relaempty' &&  cell.key_id == data.key_id) {
		// NOTE: is this logic used?
		// if grid cell had been 'relative' to other cell
		cell.relative[relative] = 1;
		cell.nearby[nearby] = 1;
		cell.markModified('relative');
		cell.markModified('nearby');
		cell.save();
	}
	else {
		cell.nearby[nearby] = 1;
		cell.markModified('nearby');
		cell.save();
	}
};

var findRelative = function(relatives, i, data) {
	dao.GridData.findById(relatives[i], function(err, cell) {
		if (err) {
			console.log('error occured while finding data by id ' + relatives[i]);
		}
		
		updateRelativeCell(relatives[i], cell, data, i + 1, i + 1);
	});
};

//app.get

//var color, keyword, content;

io.sockets.on('connection', function (socket) {
	// ajaj event which occurs document is ready on client browser
	socket.on('ajaj', function (data) {
		console.log('ajaj event occured.');
		dao.GridData.find()
		.where('gridx').gte(data.cfx-64).lt(data.cfx+64)
		.where('gridy').gte(data.cfy-24).lt(data.cfy+24)
		.where('class').in(['filled', 'relaempty'])
		.exec(function (err, cells){
			socket.emit('ajaj', cells);
		});
	});
	
	// handler for registering or updating a post
	socket.on('regist', function (data) {

		console.log('data has been registered:');
		console.log(data);
		
		// generate unique key
		if (data.key_id == null) {
			data.key_id = Number(new Date()) + (Math.floor(Math.random()*1000));
		}
		
		// update main cell
		dao.GridData.findById(data.id, function(err, cell) {
			if (err) {
				console.log('error occured while finding data by id ' + data.id);
			}
			
			if (cell == null) {
				cell = createCell(data.id);
			}
			
			cell.relative[0] = 1;
			cell.color = data.fill;
			cell.keyword = data.keyword;
			cell.key_id = data.key_id;
			cell.content = data.message;
			cell.class = 'filled';
			cell.writime = Number(new Date());
			cell.markModified('relative');
			cell.markModified('nearby');
			cell.save();
			
			console.log('cell: ' + JSON.stringify(data));
			io.sockets.emit('registpush', cell);
		});
		
		// update relative cells
		var relatives = [data.id4, data.id5, data.id6, data.id1, data.id2, data.id3];
		for (var i = 0; i < relatives.length; i++) {
			findRelative(relatives, i, data);
		};
	});
});

webserver.listen(7777);